<?php
/**
 * Created by PhpStorm.
 * User: 虚空之翼 <183700295@qq.com>
 * Date: 16/5/20
 * Time: 09:14
 */

namespace app\admin\controller;


use app\common\model\WechatDepartment;
use app\common\model\WechatDepartmentUser;
use app\common\model\WechatTag;
use app\common\model\WechatUser;
use app\common\model\WechatUserTag;
use com\common\QYWechat;
use com\wechat\TPWechat;
use think\Config;
use think\Db;
class Wechat extends Admin
{
    public function index() {

    }
    public function syncAll()
    {
        $this->synchronizeUser(true);
        $this->synchronizeDp(true);
        $this->synchronizeTag(true);

        return $this->success("一键同步成功");
    }

    public function user() {
        $name = input('name');
        $map = ['name' => ['like', "%$name%"]];
        $list = Db::name('wechatUser')
            ->where($map)
            ->order('id','desc')
            ->paginate(10);
        $department = WechatDepartment::column('id, name');
        $this->assign('list', $list);
        $this->assign('department', $department);

        return $this->fetch();
    }


    /**
     * 同步通讯录用户
     */
    public function synchronizeUser($opt=false) {
        ini_set('max_execution_time', '60');
        $Wechat = new QYWechat(Config::get('email'));
        if($Wechat->errCode != 40001) {
            return $this->error("同步出错");
        }
        /* 同步部门 */
        $list = $Wechat->getDepartment();
        /* 同步最顶级部门下面的用户 */
        $num = 0;
        foreach ($list['department'] as $key=>$value) {
            $users = $Wechat->getUserListInfo($list['department'][$key]['id']);
            foreach ($users['userlist'] as $user) {
                $num++;
                $data = [
                    'userid' => $user['userid'],
                    'name' => $user['name'],
                    'mobile' => $user['mobile'],
                    'gender' => $user['gender'],
                    'avatar' => $user['avatar'],
                    'department' => json_encode($user['department']),
                    'status' => $user['status'],
                    'order' => json_encode($user['order']),
                ];
                foreach ($user['extattr']['attrs'] as $val) {
                    switch ($val['name']){
                        case "地址":
                            $data['address'] = $val['value'];
                            break;
                        case "出生日期":
                            $data['birthday'] = $val['value'];
                            break;
                        case "学历":
                            $data['education'] = $val['value'];
                            break;
                        case "入党日期":
                            $data['partytime'] = $val['value'];
                            break;
                        case "转正日期":
                            $data['truetime'] = $val['value'];
                            break;
                        case "民族":
                            $data['nation'] = $val['value'];
                            break;
                        case "党员类型":
                            $data['partystyle'] = $val['value'];
                            break;
                    }
                }
                $data['extattr'] = json_encode($user['extattr']);
                if(WechatUser::get(['userid'=>$user['userid']])) {
                    WechatUser::where(['userid'=>$user['userid']])->update($data);
                } else {
                    WechatUser::create($data);
                }
            }
        }
        if (!$opt){
            $data = "用户数:".$num."!";
            return $this->success("同步成功", '', $data);
        }
    }

    /**
     * 同步部门
     */
    public function synchronizeDp($opt=false){
        $Wechat = new QYWechat(Config::get('email'));
        if($Wechat->errCode != 40001) {
            return $this->error("同步出错");
        }
        /* 同步部门 */
        $list = $Wechat->getDepartment();

//        WechatDepartment::where('1=1')->delete();
        foreach ($list['department'] as $key=>$value) {
            if(WechatDepartment::get($value['id'])){
                WechatDepartment::update($value);
            } else {
                WechatDepartment::create($value);
            }
        }

        /* 同步部门-用户关系表 */
//        WechatDepartmentUser::where('1=1')->delete();
        foreach ($list['department'] as $key=>$value) {
            $users = $Wechat->getUserListInfo($value['id']);
            foreach ($users['userlist'] as $user) {
                $data = ['departmentid'=>$value['id'], 'userid'=>$user['userid']];
                if(empty(WechatDepartmentUser::where($data)->find())){
                    WechatDepartmentUser::create($data);
                }
//                if($value['id'] != 1) {
//                    $data1 = ['departmentid' => 1, 'userid' => $user['userid']];     //当部门补位1时补全用户
//                    if(empty(WechatDepartmentUser::where($data1)->find())){
//                        WechatDepartmentUser::create($data1);
//                    }
//                }
            }
        }
        if (!$opt){
            $data = "同步部门数:".count($list['department'])."!";

            return $this->success("同步成功", '', $data);
        }
    }

    /**
     * 同步标签
     */
    public function synchronizeTag($opt=false){
        $Wechat = new QYWechat(Config::get('email'));
        if($Wechat->errCode != 40001) {
            return $this->error("同步出错");
        }

        /* 同步标签 */
        WechatTag::where('1=1')->delete();
        $tags = $Wechat->getTagList();

        if (isset($tags['taglist'])){
            foreach ($tags['taglist'] as $tag) {
                if(WechatTag::get(['tagid'=>$tag['tagid']])) {
                    WechatTag::where(['tagid'=>$tag['tagid']])->update($tag);
                } else {
                    WechatTag::create($tag);
                }

            }
            /* 同步标签-用户关系表 */
            WechatUserTag::where('1=1')->delete();
            foreach ($tags['taglist'] as $value) {
                $users = $Wechat->getTag($value['tagid']);
                if(empty($users['userlist'])){
                    // 同步标签内的部门
                    if (!empty($users['partylist'])){
                        foreach ($users['partylist'] as $user){
                            $info = $Wechat->getUserListInfo($user);
                            foreach ($info['userlist'] as $val){
                                $data = ['tagid' => $value['tagid'],'userid' => $val['userid']];
                                if(empty(WechatUserTag::where($data)->find())){
                                    WechatUserTag::create($data);
                                }
                            }
                        };
                    }
                }else{
                    foreach ($users['userlist'] as $user) {
                        $data = ['tagid'=>$value['tagid'], 'userid'=>$user['userid']];
                        if(empty(WechatUserTag::where($data)->find())){
                            WechatUserTag::create($data);
                        }
                    }
                    // 同步标签内的部门
                    if (!empty($users['partylist'])){
                        foreach ($users['partylist'] as $user){
                            $info = $Wechat->getUserListInfo($user);
                            foreach ($info['userlist'] as $val){
                                $data = ['tagid' => $value['tagid'],'userid' => $val['userid']];
                                if(empty(WechatUserTag::where($data)->find())){
                                    WechatUserTag::create($data);
                                }
                            }
                        };
                    }
                }
            }
        }
        if (!$opt){
            $data = "同步标签数:".count($tags['taglist'])."!";

            return $this->success("同步成功", '', $data);
        }
    }


    public function department(){
        $list = Db::name('wechatDepartment')
            ->order('id','desc')
            ->paginate(10);
        $this->assign('list', $list);

        return $this->fetch();

    }

    public function tag(){
        $list = Db::name('wechatTag')
            ->order('id','desc')
            ->paginate(10);
        $this->assign('list', $list);

        return $this->fetch();
    }


}